const Koa = require('koa');
const consola = require('consola');
const session = require('koa-session');
const bodyParser = require('koa-bodyparser');
const cors = require('@koa/cors');
const { Nuxt, Builder } = require('nuxt');

const app = new Koa();

// Import and Set Nuxt.js options
const config = require('../nuxt.config.ts');
const routes = require('./routes');
let configServer = require('../config');

config.dev = !(app.env === 'production');

app.keys = ['marketing']; // cookie
const sessionConfig = {
    key: 'marketing',
    maxAge: 7 * 60 * 60 * 24 * 1000, // 7 day
    overwrite: true,
    httpOnly: false,
    signed: true,
    renew: false,
    rolling: true
};

async function start() {
    // Instantiate nuxt.js
    const nuxt = new Nuxt(config);

    const {
        host = process.env.HOST || '127.0.0.1',
        port = process.env.PORT || configServer.PORT
    } = nuxt.options.server;

    app.use(session(sessionConfig, app));
    app.use(bodyParser());
    app.use(cors());
    app.use(routes.routes(), routes.allowedMethods());
    // Build in development
    if (config.dev) {
        const builder = new Builder(nuxt);
        await builder.build();
    } else {
        await nuxt.ready();
    }

    app.use((ctx: any) => {
        ctx.status = 200;
        ctx.req.session = ctx.session; // 缺少这个会导致 vuex store 无效
        ctx.respond = false; // Bypass Koa's built-in response handling
        ctx.req.ctx = ctx; // This might be useful later on, e.g. in nuxtServerInit or with nuxt-stash
        nuxt.render(ctx.req, ctx.res);
    });
    app.listen(port, host);
    consola.ready({
        message: `Server listening on http://${host}:${port}`,
        badge: true
    });
}

start();
